﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Navigation;
using Hammock;
using Hammock.Web;
using Microsoft.Phone.Controls;
using MyMeetup.ViewModels;
using Newtonsoft.Json;

namespace MyMeetup
{
    public partial class MainPage : PhoneApplicationPage
    {
        private MainPageViewModel _viewModel;
        private List<Photo> _userPhotos;
        protected List<Activity> _news;
        private Popup _popup;
        private bool _loaded = false;
        private bool networkError = false;

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            _viewModel = this.DataContext as MainPageViewModel;
            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }


        private void SearchClicked(object sender, System.EventArgs e)
        {
            var vm = DataContext as MainPageViewModel;
            if(vm != null) vm.SearchClick.Execute(null);
        }


        private void SettingsClicked(object sender, System.EventArgs e)
        {
            var vm = DataContext as MainPageViewModel;
            if(vm != null) vm.SettingsClick.Execute(null);
        }


        private void LogoutClicked(object sender, EventArgs e)
        {
            var vm = DataContext as MainPageViewModel;
            if (vm != null) vm.LogoutClick.Execute(null);
        }
        


        // Load data for the ViewModel Items
        private void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            ClearBackStack();
        }

        private void ClearBackStack()
        {
            
            while(NavigationService.CanGoBack)
            {
                NavigationService.RemoveBackEntry();
            }
        }




        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //App.Settings.AddOrUpdateValue("MainViewModel", _viewModel);
            App.Settings.News = _viewModel.LatestNews;
            //App.Settings.MyGroups = _viewModel.UserGroups;
            App.Settings.UpcomingEvents = _viewModel.UpcomingEvents;

            base.OnNavigatedFrom(e);

        }

        
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            _viewModel = DataContext as MainPageViewModel;

            _viewModel.LatestNews = App.Settings.News;
            //_viewModel.UserGroups = App.Settings.MyGroups;
            _viewModel.UpcomingEvents = App.Settings.UpcomingEvents;

            base.OnNavigatedTo(e);
        }


    }
}